/*
 * Copyright 2008,2009,2010 Daniel Freitas
 *
 * This file is part of DMF Generic DAO.
 *
 * DMF Generic DAO is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
 * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * DMF Generic DAO is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with DMF Generic DAO. If not, see
 * <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dmf.genericdao.hibernate;

import java.io.Serializable;
import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.IntroductionInterceptor;
import org.springframework.aop.ProxyMethodInvocation;

import com.googlecode.dmf.genericdao.DaoQueryExecutor;
import com.googlecode.dmf.genericdao.GenericDao;
import com.googlecode.dmf.genericdao.GenericlessGenericDao;
import com.googlecode.dmf.genericdao.util.Reflectioner;

/**
 * Hibernate generic DAO advisor. Dispatches GenericDao method calls to the advised
 * {@link com.googlecode.dmf.genericdao.hibernate.HibernateGenericDao} and methods defined in subinterfaces to
 * {@link com.googlecode.dmf.genericdao.DaoQueryExecutor}.
 *
 * @author <a href="mailto:daniel.mfreitas@gmail.com">Daniel Freitas</a>
 */
public class HibernateDaoAdvisor implements IntroductionInterceptor {

    private Method findByIdMethod;
    private Method findAllMethod;
    private final Reflectioner reflectioner;
    private final DaoQueryExecutor queryExecutor;

    /**
     * Creates an instance of this class.
     *
     * @param reflectioner
     *            The {@link Reflectioner} utility class instance to use for reflection.
     */
    public HibernateDaoAdvisor(final Reflectioner reflectioner, final DaoQueryExecutor queryExecutor) {
        this.reflectioner = reflectioner;
        this.queryExecutor = queryExecutor;

        try {
            findByIdMethod = reflectioner.getMethodByName(GenericDao.class, "findById", Serializable.class);
            findAllMethod = reflectioner.getMethodByName(GenericDao.class, "findAll", new Class[] {});
        } catch (SecurityException e) {
            throw new IllegalStateException("Unable to access method information from the generic dao calss through "
                    + "reflection. It was not possible to create the default hibernate dao.", e);
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException("Unable to access method information from the generic dao calss through "
                    + "reflection. It was not possible to create the default hibernate dao.", e);
        }
    }

    /**
     *
     * {@inheritDoc}
     *
     * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
     */
    @Override
    public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
        Object result = null;
        Class<?> entityClass = null;

        entityClass = getEntityClass(methodInvocation);

        if (entityClass == null) {
            throw new IllegalStateException("Unable to determine the Class of the entity a dao is responsible for.");
        }

        if (methodInvocation.getMethod().equals(findByIdMethod)) {
            GenericlessGenericDao<?> target = (GenericlessGenericDao<?>) methodInvocation.getThis();
            result = target.findById(entityClass, (Serializable) methodInvocation.getArguments()[0]);
        } else if (methodInvocation.getMethod().equals(findAllMethod)) {
            GenericlessGenericDao<?> target = (GenericlessGenericDao<?>) methodInvocation.getThis();
            result = target.findAll(entityClass);
        } else if (methodInvocation.getMethod().getDeclaringClass().equals(GenericDao.class)) {
            result = methodInvocation.proceed();
        } else {
            result = queryExecutor.executeQueryForMethod(methodInvocation.getMethod(), methodInvocation.getArguments());
        }

        return result;
    }

    private Class<?> getEntityClass(final MethodInvocation methodInvocation) {

        ProxyMethodInvocation reflectiveMethodInvocation = (ProxyMethodInvocation) methodInvocation;
        Object obj = reflectiveMethodInvocation.getProxy();

        return reflectioner.getDaoEntityClass(obj.getClass());
    }

    /**
     *
     * {@inheritDoc}
     *
     * @see org.springframework.aop.DynamicIntroductionAdvice#implementsInterface(java.lang.Class)
     */
    @Override
    public boolean implementsInterface(final Class<?> intf) {
        return intf.isInterface() && intf.isAssignableFrom(HibernateDaoAdvisor.class);
    }
}
